程序流程控制

程序流程控制

比较运算符和 Boolean 类型的值

运算符 描述 示例
== 判断内容是否相等,满足为 True,不满足为 False 如 a=3,b=3,则 (a== b) 为 True
!= 判断内容是否不相等,满足为 True,不满足为 False 如 a=1,b=3,则 (a != b) 为 True
> 判断运算符左侧内容是否大于右侧 满足为 True,不满足为 False 如 a=7,b=3,则 (a > b)  为 True
< 判断运算符左侧内容是否小于右侧 满足为 True,不满足为 False 如 a=3,b=7,则 (a < b)  为 True
>= 判断运算符左侧内容是否大于等于右侧 满足为 True,不满足为 False 如 a=3,b=3,则 (a >= b) 为 True
<= 判断运算符左侧内容是否小于等于右侧 满足为 True,不满足为 False 如 a=3,b=3,则 (a <= b) 为 True

逻辑表达式:python 中没有 &&!, || 这 3 个运算符(但是有 !=),在逻辑表达式中写成这 3 个会报逻辑错误的。要实现同样的功能,要写成 and,not,or。

类型不同,通过 == 比较,一定是 False,反之通过 != 比较,一定是 True

简单实践:

true_value = True
print(true_value, type(true_value))
false_value = False
print(false_value, type(false_value))
greater = 10 > 5
print(f"{greater}, {type(greater)}")
# == 等效于 equal = "12133".__eq__("12133")
equal = "12133" == "12133"
print(equal)
print("--------------")
equal = 12133 == "12133"
print(equal)
print("--------------")
print(f"{1200000 == 1200000}")
print("--------------")
# 类型转换函数 bool() ,只要参数不是数字0,就返回True,否则返回False
print(bool(1))
print(bool(10))
print(bool(0))
print(bool(-120))
print(bool("0"))
print(bool("-120"))
print("--------------")
# 逻辑运算符
print(not (1 != 1))
print((1 != 1) or (1 != 2))
print((1 == 1) and (2 == 2))

当一个值被用作条件表达式时,它会被隐式地转换为布尔类型,可能是通过 bool() 函数来确定其是 True 还是 False

空字符串、空列表、空元组、空字典、数字 0 、None 等对象的布尔值为 False

简单实践:

# False
print(bool(""))
# False
print(bool(list()))
# False
print(bool(tuple()))
# False
print(bool(set()))
# False
print(bool(dict()))
# False
print(bool(0))
# False
print(bool(None))
# 使用 not 将其变成 True
# True
print(bool(not ""))

if list():
    print("True")
else:
    print("False")

# 类型不同,通过`==`比较,一定是`False`,反之通过`!=`比较,一定是`True`。
if '' != True:
    print("'' 不为 True")

if '' != False:
    print("'' 不为 False")

# 会自动调用bool()函数判断其是 True 还是 False
# bool('') False
if '':
    print("'' 逻辑上为 True")
else:
    print("'' 逻辑上为 False")

# bool( not '') True
if not '':
    print(" not '' 为true ")

条件语句

简单看看即可,非常简单

# 引入随机数类
# import random
#
# num =  random.randint(0,10)
# print(f"{num}的类型是:{type(num)}")

age = input("please enter your age:")
age_int = int(age)
if age_int < 18:
    # Python中通过缩进(一般是四个空格)来确定代码的归属(范围)
    # 这个跟Java不同,Java通过{}确定归属(范围)
    print("i am a child")
elif age_int >= 18 and age_int < 50:
    print("i am a adult ")
else:
    print("i am a old man")
# 这行语句因为缩进跟 print("i am a old man") 不同,所以不是else语句的执行范围
print("程序结束!")



if int(input("请输入你的年龄:")) < 18:
    print("i am a child")
elif int(input("请输入你的身高(cm):")) < 170:
    print("i am a short ")
else:
    print("i am a normal adult")
print("程序结束!")



if int(input("input a num that greater than 5 :")) > 5:
    print("success")
    if int(input("input a num that greater than 200 :")) > 200:
        print("success")
    else:
        print("error")
else:
    print("error")

循环语句

while 循环

# 计算 1 到 100 的和
sum = 0
i = 1
while i <= 100:
    sum += i
    i += 1
print(f"amount is {sum}")

# 这个import语句有点像在Java的一个类中引入另一个类
import random

# 目标数字
# 获取 1 -10 的随机数
target_num = random.randint(0, 10)
print(f"target num is {target_num}")
# 总共猜5次
action_account = 3
guess_count = 0

while guess_count < action_account:
    guess_count += 1
    if int(input("请输出目标数字:")) != target_num:
        print("猜错了")
    else:
        print("猜对了")
        break
print(f"总共猜了{guess_count}次")

# while的嵌套 输出九九乘法表
outer_count = 9
outer_index = 1
while outer_index <= outer_count:
    inner_index = 1
    while inner_index <= outer_index:
        print(f"{outer_index}*{inner_index}={outer_index * inner_index}\t", end="")
        inner_index += 1
    # 默认就是输出一个换行
    print()
    # 这是两个换行,换两行
    # print("\n")
    outer_index += 1
print("输出结束")

for 循环

除了 while 循环语句外,Python 同样提供了 for 循环语句。两者能完成的功能基本差不多,但仍有一些区别:

简单实践:

name = "xiashuo.xyz"
# 循环字符串中的字符
for i in name:
    print(f"{i}", end='')
print("-------")

# 通过range可以获取一个简单的数字序列
# 从0(包含)开始到10(不包含)
# 注意,变量类型是 <class 'range'>
print(type(range(0, 10)))
# for循环
for i in range(10):
    print(f"{i}")
print("-------")
# 从5(包含)开始到10(不包含)
for i in range(5, 10):
    print(f"{i}")
print("-------")
# 从5(包含)开始到10(不包含),设置序列的步长(step)为2,即每隔2输出一个数字,默认的step是1
for i in range(5, 10, 2):
    print(f"{i}")
print("-------")

# 如何获取被便利元素的索引呢?用 enumerate 方法即可
for inx, val in enumerate(name):
    print(f"{inx}处的元素是{val}")

# 从 3 到20,每隔5个数字输出一次
for index, ele in enumerate(range(3, 20, 5)):
    print(f"{index}: {ele}")
# 注意,在for循环的外部,访问index和ele,是可以访问到的,这一点跟Java很不一样
# 这样是违反规范的,不建议这样做
# 可以看到爆黄色警告
print(f"在for循环的外部访问for循环的内部的临时变量:{index}: {ele}")
# 如果你确实需要在for循环的外部来访问,你可以先把for循环内部需要用到的变量定义好,然后就for循环的时候会直接使用这些变量
index_new = 0
ele_new = 0
# for循环会直接使用
for index_new, ele_new in enumerate(range(3, 20, 5)):
    print(f"{index_new}: {ele_new}")
print(f"在for循环的外部访问变量:{index_new}: {ele_new}")

# 九九乘法表 for循环版本
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{i}*{j}={i * j}\t", end="")
    print()
print("输出结束")

for 循环的作用域 -- 很神奇

临时变量,在编程规范上,作用范围(作用域),只限定在 for 循环内部。但是如果在 for 循环外部访问临时变量,实际上是可以访问到的,在编程规范上,是不允许、不建议这么做的

这个跟 Java 很不一样,在 Java 中,在 for 循环的外部访问 for 循环的临时变量,是访问不到的

简单实践:

# 从 3 到20,每隔5个数字输出一次
for index, ele in enumerate(range(3, 20, 5)):
    print(f"{index}: {ele}")
# 注意,在for循环的外部,访问index和ele,是可以访问到的,这一点跟Java很不一样
# 这样是违反规范的,不建议这样做
# 可以看到爆黄色警告
print(f"在for循环的外部访问for循环的内部的临时变量:{index}: {ele}")

此时,在 print(f"在for循环的外部访问for循环的内部的临时变量:{index}: {ele}") 中 index 变量上爆黄色警告

输出:

0: 3
1: 8
2: 13
3: 18
在for循环的外部访问for循环的内部的临时变量:3: 18

如果你确实需要在 for 循环的外部来访问,你可以先把 for 循环内部需要用到的变量定义好,然后就 for 循环的时候会直接使用这些变量,然后我们也可以很自然的在 for 循环结束之后,继续使用这些变量

# 如果你确实需要在for循环的外部来访问,你可以先把for循环内部需要用到的变量定义好,然后就for循环的时候会直接使用这些变量
index_new = 0
ele_new =0
# for循环会直接使用
for index_new, ele_new in enumerate(range(3, 20, 5)):
    print(f"{index_new}: {ele_new}")
print(f"在for循环的外部访问变量:{index_new}: {ele_new}")

此时 index_new 变量上没有黄色报警,输出:

0: 3
1: 8
2: 13
3: 18
在for循环的外部访问变量:3: 18

for 循环同时处理多个值

同时输出多个值

for 循环有一个很有意思的特性, 即如果被迭代的容器对象的元素本身也可以迭代,则可以使用多个对象来承接,而如果被迭代的容器对象的元素无法迭代,但是你用多个对象承接,则会报错

本质上还是基于 Python 的自动解包特性,关于 Python 的解包,请看《Python 解包.md

常规的方式,用单个对象承接

# 用单个对象承接 字符串
list_for = ["aa", "bb", "cc", "dd"]
for item in list_for:
    print(item, end=" ")
print()

输出:

aa bb cc dd 

因为 字符串本身是字符的序列,可以迭代,因此可以用多个对象承接,同时承接的变量的数量必须与元素中可迭代的数量相同

在下面的例子中,会尝试迭代容器对象(列表,元组,集合,字典)的每一个元素,然后顺序赋值给声明的变量,比如 char1, char2

# 输出 aa bb cc dd
list_for_2 = ["ab", "cd", "ef", "gh"]
for char1, char2 in list_for_2:
    print(f"{char1}-{char2}", end=" ")
print()

输出:

a-b c-d e-f g-h 

如果容器对象的元素本身(是数字或者 Boolean,而不是字符串、列表元组,集合,字典),无法迭代,则会报错

# TypeError: cannot unpack non-iterable int object
list_for_3 = [12, 34, 56, 78]
for num1, num2 in list_for_3:
    print(f"{num1}-{num2}", end=" ")
print()

如果可迭代的对象的每个可迭代的元素的长度是四,但是你只声明了两个接收的值,那么依然会报错,此时,你可以在变量前面加 * ,加 * 的变量会变成一个列表

# 因为结果是集合,是无序的,所以输出结果不是确定的
list_for_3 = {"a12", "b45", "c78", "d89"}
for index_3, *val_3 in list_for_3:
    print(f"{index_3}-{val_3}", end=" ")
print()

输出:

b-['4', '5'] c-['7', '8'] d-['8', '9'] a-['1', '2'] 
同时输入多个序列

for 通过结合 zip 函数,我们可以在一个循环中同时循环多个序列。

这在 Java 里面也是没有的

通过 zip 函数我们可以将多个序列中相同索引的元素放到一个元组中,然后将所有的元组组成列表返回,返回的列表的长度将由长度最小的序列决定。zip 函数的结果类型是 zip

# 混合三个序列
list_a = [1, 2, 3]
list_b = ["a", "b", "c"]
tuple_c = True, False
result = zip(list_a, list_b, tuple_c)
# 结果类型为 zip
print(result, type(result))
for a, b, c, in result:
    print(a, b, c)

输出:

<zip object at 0x00000291AE8ACF00> <class 'zip'>
1 a True
2 b False